<template>
  <div class="creators-page">
    <!-- 主要内容区域 -->
    <div class="creators-content">
      <!-- 桌面端：上下布局 -->
      <div v-if="!isMobile" class="desktop-layout">
        <!-- 顶部筛选器 -->
        <div class="creators-filter-section">
          <creator-filter
            :categories="categories"
            :loading="categoriesLoading"
            @filter-change="handleFilterChange"
          />
        </div>

        <!-- 创作者列表 -->
        <div class="creators-main">
          <creator-list
            :creators="creators"
            :loading="loading"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            :view-mode="viewMode"
            @page-change="handlePageChange"
            @view-mode-change="handleViewModeChange"
            @creator-click="handleCreatorClick"
          />
        </div>
      </div>

      <!-- 移动端：简化布局 -->
      <div v-else class="mobile-layout">
        <!-- 移动端筛选器 -->
        <div class="mobile-filter-section">
          <creator-filter
            :categories="categories"
            :loading="categoriesLoading"
            :mobile="true"
            @filter-change="handleFilterChange"
          />
        </div>

        <!-- 移动端创作者列表 -->
        <div class="mobile-content">
          <creator-list
            :creators="creators"
            :loading="loading"
            :total="total"
            :current-page="currentPage"
            :page-size="pageSize"
            :view-mode="'grid'"
            :mobile="true"
            @page-change="handlePageChange"
            @creator-click="handleCreatorClick"
          />
        </div>
      </div>
    </div>

    <!-- 创作者详情抽屉 -->
    <n-drawer
      v-model:show="showCreatorDetail"
      :width="isMobile ? '100%' : '600px'"
      placement="right"
      :mask-closable="true"
      :show-mask="true"
      :close-on-esc="true"
    >
      <n-drawer-content title="创作者详情" :native-scrollbar="false">
        <creator-detail
          v-if="selectedCreatorId"
          :creator-id="selectedCreatorId"
          @close="handleCloseDetail"
        />
      </n-drawer-content>
    </n-drawer>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { getCreatorsList, getCreatorCategories } from '@/api/creators'
import type { CreatorDetail as CreatorDetailType, CreatorFilter as CreatorFilterType, CreatorViewMode, CreatorsResponse } from '@/types/creators'
import CreatorFilter from './components/CreatorFilter.vue'
import CreatorList from './components/CreatorList.vue'
import CreatorDetail from './components/CreatorDetail.vue'


// 引入创作者页面样式
import '@/styles/components/creators/CreatorsPage.css'

// 路由相关
const route = useRoute()
const router = useRouter()
const message = useMessage()

// 响应式状态
const isMobile = ref(false)
const loading = ref(false)
const categoriesLoading = ref(false)

// 创作者数据
const creators = ref<CreatorDetailType[]>([])
const categories = ref<string[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(12)

// 筛选参数
const filterParams = ref<Partial<CreatorFilterType>>({
  page: 1,
  limit: 12,
  category: '',
  keyword: '',
  creator_type: 3,
  status: ''
})

// 视图模式
const viewMode = ref<CreatorViewMode>('grid')

// 创作者详情
const showCreatorDetail = ref(false)
const selectedCreatorId = ref<number | null>(null)

// 移动端检测
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 获取创作者列表
const fetchCreators = async () => {
  try {
    loading.value = true
    console.log('正在获取创作者列表，参数:', filterParams.value)
    const response = await getCreatorsList(filterParams.value)
    console.log('创作者列表响应:', response)

    if (response.code === 1) {
      creators.value = (response.data as unknown as CreatorsResponse).list
      total.value = (response.data as unknown as CreatorsResponse).total
      currentPage.value = (response.data as unknown as CreatorsResponse).current_page
    } else {
      console.error('API返回错误:', response)
      message.error(response.msg || '获取创作者列表失败')
    }
  } catch (error: any) {
    console.error('获取创作者列表失败:', error)
    message.error('获取创作者列表失败: ' + (error?.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    console.log('正在获取分类列表...')
    const response = await getCreatorCategories()
    console.log('分类列表响应:', response)

    if (response.code === 1) {
      // API直接返回字符串数组
      categories.value = (response.data as unknown as string[]) || []
      console.log('分类列表设置成功:', categories.value)
    } else {
      console.error('分类API返回错误:', response)
      message.error(response.msg || '获取分类列表失败')
    }
  } catch (error: any) {
    console.error('获取分类列表失败:', error)
    message.error('获取分类列表失败: ' + (error?.message || '未知错误'))
  } finally {
    categoriesLoading.value = false
  }
}

// 处理筛选变化
const handleFilterChange = (newFilter: Partial<CreatorFilterType>) => {
  filterParams.value = { ...filterParams.value, ...newFilter, page: 1 }
  fetchCreators()
}

// 处理分页变化
const handlePageChange = (page: number) => {
  filterParams.value.page = page
  fetchCreators()
}

// 处理视图模式变化
const handleViewModeChange = (mode: CreatorViewMode) => {
  viewMode.value = mode
  localStorage.setItem('creators-view-mode', mode)
}

// 处理创作者点击
const handleCreatorClick = (creatorId: number) => {
  selectedCreatorId.value = creatorId
  showCreatorDetail.value = true
}

// 处理关闭详情
const handleCloseDetail = () => {
  showCreatorDetail.value = false
  selectedCreatorId.value = null
}

// 初始化视图模式
const initViewMode = () => {
  const savedMode = localStorage.getItem('creators-view-mode') as CreatorViewMode
  if (savedMode && ['grid', 'list'].includes(savedMode)) {
    viewMode.value = savedMode
  }
}

// 生命周期
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
  initViewMode()
  
  // 初始化数据
  fetchCategories()
  fetchCreators()
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})
</script>

<style scoped>
.creators-page {
  width: 100%;
  padding: 0 16px;
}

.creators-content {
  min-height: 600px;
}

.desktop-layout {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.creators-filter-section {
  background: var(--n-card-color);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid var(--n-border-color);
}

.creators-main {
  flex: 1;
}

.mobile-layout {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mobile-filter-section {
  background: var(--n-card-color);
  border-radius: 8px;
  padding: 12px;
  border: 1px solid var(--n-border-color);
}

.mobile-content {
  flex: 1;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .creators-page {
    padding: 0 12px;
  }

  .desktop-layout {
    display: none;
  }
}

@media (min-width: 769px) {
  .mobile-layout {
    display: none;
  }
}
</style>
